package cn.buk.qms.web;

import cn.buk.common.util.DateUtil;
import cn.buk.qms.service.FlightOrderService;
import cn.buk.tms.misc.ExportExcelService;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

/**
 * 下载控制器
 */
@RestController
public class DownloadController extends BaseController {

  @Autowired
  private FlightOrderService flightOrderService;

  @Autowired
  private ExportExcelService exportExcelService;


  /**
   * 下载机票订单乘机人的团客格式
   */
  @RequestMapping(value = "/order/flight/{id}/groupPassenger/{carrierCode}")
  public void downloadGroupPassenger(HttpServletRequest request, HttpServletResponse response,
                                     @PathVariable("id") final int orderId,
                                     @PathVariable("carrierCode") final String carrierCode
  ) {
    final int enterpriseId = getEnterpriseId(request);
    final int userId = getUserId(request);
    final String username = getUsername(request);
    var dto = flightOrderService.getFlightOrderDetail(enterpriseId, userId, orderId);
    flightOrderService.appendFlightOrderLog(enterpriseId, username, orderId, "下载" + carrierCode + "团客格式数据");
    //输出
    try {
      ServletOutputStream out = response.getOutputStream();
      String filename = "flight-passenger-" + DateUtil.formatDate(DateUtil.getCurDateTime(), "yyyyMMddHHmmss") + ".xlsx";
      response.setHeader("Content-Disposition", "inline; filename=" + filename);
      response.setContentType("application/ms-excel;charset=UTF-8");

      Workbook workbook = WorkbookFactory.create(true); //xlsx
      Sheet sheet = workbook.createSheet();


      exportExcelService.exportFlightOrderPassenger(enterpriseId, dto, sheet, carrierCode);


      workbook.write(out);
      out.flush();
      out.close();
    } catch (Exception e) {
      e.printStackTrace();
    }
  }

}
